// hooks/useAuth.tsx
"use client"

import { useState, useEffect, useCallback, createContext, useContext, ReactNode } from 'react'
import { authAPI } from '@/lib/authapi'
import { TokenManager } from '@/lib/api-client'
import type { User, LoginRequest, AuthResponse } from '@/types/auth'

interface AuthContextType {
  user: User | null
  isLoading: boolean
  isAuthenticated: boolean
  login: (credentials: LoginRequest) => Promise<{ success: boolean; message?: string }>
  logout: () => Promise<void>
  refreshUser: () => Promise<void>
  checkAuth: () => Promise<void>
}

const AuthContext = createContext<AuthContextType | null>(null)

export function useAuth() {
  const context = useContext(AuthContext)
  if (!context) {
    // 如果没有 Provider，返回一个基本的实现
    return useAuthState()
  }
  return context
}

// 基本的认证状态钩子
function useAuthState() {
  const [user, setUser] = useState<User | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isAuthenticated, setIsAuthenticated] = useState(false)

  // 检查认证状态
  const checkAuth = useCallback(async () => {
    try {
      const accessToken = TokenManager.getAccessToken()
      if (!accessToken) {
        setUser(null)
        setIsAuthenticated(false)
        return
      }

      const userData = await authAPI.getProfile() as User
      setUser(userData)
      setIsAuthenticated(true)
    } catch (error) {
      console.error('Auth check failed:', error)
      TokenManager.clearTokens()
      setUser(null)
      setIsAuthenticated(false)
    } finally {
      setIsLoading(false)
    }
  }, [])

  // 登录
  const login = useCallback(async (credentials: LoginRequest) => {
    try {
      setIsLoading(true)
      console.log('开始登录，发送数据:', {
        email: credentials.email,
        user_type: credentials.user_type,
        // 不记录密码
      })
      
      const response = await authAPI.login(credentials) as AuthResponse
      console.log('登录响应:', response)
      
      if (response.tokens) {
        TokenManager.setTokens(response.tokens.access, response.tokens.refresh)
        setUser(response.user)
        setIsAuthenticated(true)
        console.log('登录成功:', response.user)
        return { success: true }
      }
      
      return { success: false, message: response.message || '登录失败' }
    } catch (error: any) {
      console.error('登录错误详情:', error)
      let message = '登录失败'
      
      // 优先使用 error.message，因为 authapi.ts 中已经正确处理了错误格式
      if (error.message) {
        message = error.message
      } else if (error.response?.data) {
        // 备用方案：直接从响应数据中获取
        const errorData = error.response.data
        if (typeof errorData === 'string') {
          message = errorData
        } else if (errorData.detail) {
          message = errorData.detail
        } else if (errorData.message) {
          message = errorData.message
        } else if (errorData.error) {
          message = errorData.error
        }
      }
      
      console.error('最终错误信息:', message)
      return { success: false, message }
    } finally {
      setIsLoading(false)
    }
  }, [])

  // 登出
  const logout = useCallback(async () => {
    try {
      const refreshToken = TokenManager.getRefreshToken()
      if (refreshToken) {
        // 尝试调用后端登出API，但不阻塞本地清理
        try {
          await authAPI.logout(refreshToken)
          console.log('后端登出成功')
        } catch (apiError) {
          console.warn('后端登出API调用失败，但继续执行本地清理:', apiError)
          // 即使后端API失败，也要继续执行本地清理
        }
      }
    } catch (error) {
      console.error('登出过程中发生错误:', error)
    } finally {
      // 无论后端API是否成功，都要清理本地状态
      TokenManager.clearTokens()
      setUser(null)
      setIsAuthenticated(false)
      console.log('本地登出状态清理完成')
    }
  }, [])

  // 刷新用户信息
  const refreshUser = useCallback(async () => {
    try {
      if (!isAuthenticated) return
      
      const userData = await authAPI.getProfile() as User
      setUser(userData)
    } catch (error) {
      console.error('Refresh user failed:', error)
      // 如果刷新失败，可能是 token 过期，执行登出
      await logout()
    }
  }, [isAuthenticated, logout])

  // 初始化时检查认证状态
  useEffect(() => {
    checkAuth()
  }, [checkAuth])

  return {
    user,
    isLoading,
    isAuthenticated,
    login,
    logout,
    refreshUser,
    checkAuth
  }
}

// AuthProvider 组件
export function AuthProvider({ children }: { children: ReactNode }) {
  const auth = useAuthState()
  
  return (
    <AuthContext.Provider value={auth}>
      {children}
    </AuthContext.Provider>
  )
}